package cs2340.droidceptiontodo.test;


import java.util.ArrayList;

import cs2340.droidceptiontodo.Database;
import cs2340.droidceptiontodo.ToDoItem;
import cs2340.droidceptiontodo.UserAccount;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
/**
 * Android JUnit test for the Database class
 * Tests GetSetting and CreateUser methods
 * 
 * @author Roberta Reusch-Lewis
 *
 */
public class DatabaseTest extends AndroidTestCase {
	private Database db;
	private static final String TEST_FILE_PREFIX = "test_";
	
	/**
	 * Initializes database
	 */
	protected void setUp() throws Exception {
		RenamingDelegatingContext context 
			= new RenamingDelegatingContext(getContext(), TEST_FILE_PREFIX);
		db = new Database(context);
		db.open();
	}
	/**
	 * Checks that database is not null
	 */
	public void testPreConditions() {
	    assertNotNull(db);
	}
	/**
	 * Makes sure a user can be saved in the database
	 */
	public void testCreateUser() {
		String login1 = "user";
		String password1 = "pass";
		String email1 = "user@blah.com";
		String name1 = "User Name";
		// User cannot login before account is created
		assertEquals(-1, db.checkUser(login1, password1));
		db.createUser(login1, password1, email1, name1);
		// Incorrect password should not let the user log in
		assertEquals(0, db.checkUser(login1, "passs"));
		// User can log in correctly
		assertEquals(1, db.checkUser(login1, password1)); 
		// New user should have no items
		assertTrue(db.getItems(login1).isEmpty());
		// Can log in the user:
		UserAccount newUser = new UserAccount(login1, password1, email1, name1);
		Database.currentUser = newUser;	
		assertTrue(db.getUser().equals(newUser));
		
		String login2 = "uSeR";
		db.createUser(login2, password1, email1, name1);
		// Only login should distinguish users
		assertEquals(1, db.checkUser(login2, password1));
		assertTrue(db.getItems(login1).isEmpty());
		assertEquals(1, db.checkUser(login1, password1));
	}
	/**
	 * Makes sure that a set setting can be found and returned
	 * from the database
	 * 
	 */
	public void testGetSetting() {
		String setting1 = "setting1";
		String setting2 = "setting2";
		String value1 = "true";
		String value2 = "false";
		db.setSetting(setting1, value1);
		// Should be able to get setting1
		assertEquals(value1, db.getSetting(setting1));
		// New setting should not change value of setting1
		db.setSetting(setting2, value2);
		assertEquals(value1, db.getSetting(setting1));
		// Can get setting2
		assertEquals(value2, db.getSetting(setting2));
		// Changes to setting work
		db.setSetting(setting2, value1);
		assertEquals(value1, db.getSetting(setting2));
		// Null value works
		db.setSetting(setting1, "");
		assertEquals("", db.getSetting(setting1));
	}
	/**
	 * Closes the database
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
		db.close();
		db = null;
	}
}
